package main

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"errors"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"os"
	"strings"
)

func RequestJson(method string, url string, data map[string]interface{}) (ApiResponse, error) {
	var apiResponse ApiResponse
	jsonStr, _ := json.Marshal(data)
	req, err := http.NewRequest(method, url, bytes.NewBuffer(jsonStr))
	if err != nil {
		return apiResponse, err
	}
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return apiResponse, err
	}
	defer resp.Body.Close()
	bodyBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return apiResponse, err
	}
	apiResponse, err = ParseBean[ApiResponse](bodyBytes)
	if err != nil {
		return apiResponse, err
	}
	return apiResponse, nil
}
func DownloadBase64(url string, destination string) (string, error) {
	response, err := http.Get(url)
	if err != nil {
		return "", err
	}
	defer response.Body.Close()
	if response.StatusCode != http.StatusOK {
		return "", errors.New("failed to download file")
	}
	imageData, err := io.ReadAll(response.Body)
	if err != nil {
		return "", err
	}
	res := strings.ReplaceAll(string(imageData), "\"", "")
	encodedImage := res[strings.Index(res, ",")+1:]
	reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(encodedImage))
	file, err := os.Create(destination)
	if err != nil {
		return "", err
	}
	defer file.Close()
	_, err = io.Copy(file, reader)
	if err != nil {
		return "", err
	}
	return destination, nil
}
func UploadFile(filePath string, url string, token string, proposalNo string) error {
	file, err := os.Open(filePath)
	if err != nil {
		return err
	}
	defer file.Close()
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	part, err := writer.CreateFormFile("file", filePath)
	if err != nil {
		return err
	}
	_, err = io.Copy(part, file)
	if err != nil {
		return err
	}
	writer.WriteField("policyNumber", proposalNo)
	err = writer.Close()
	if err != nil {
		return err
	}
	request, err := http.NewRequest("POST", url, body)
	if err != nil {
		return err
	}
	request.Header.Set("Content-Type", writer.FormDataContentType())
	request.Header.Set("Authorization", token)
	client := &http.Client{}
	response, err := client.Do(request)
	if err != nil {
		return err
	}
	defer response.Body.Close()
	if response.StatusCode == http.StatusOK {
		println("文件上传成功！")
	} else {
		println("文件上传失败，状态码：%d\n", response.StatusCode)
	}
	return nil
}
